package com.datang.yourtomcat02;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/*
 * @auther 顶风少年
 * @mail dfsn19970313@foxmail.com
 * @date 2019-09-16 17:57
 * @notify socket服务端
 * @version 1.0
 */

public class HttpServer {

    //停止命令
    private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
    //停止标识符
    private boolean shutdown = false;

    /*
     * @author 顶风少年
     * @date 2019/9/16 18:54
     * @mail dfsn199703132038@foxmail.com
     * @throws
     * @param
     * @result void
     * @notify 监听服务
     * version 1.0
     */
    public void await() {
        ServerSocket serverSocket = null;
        int port = 8080;
        try {
            //创建 服务端
            serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
        //循环监听
        while (!shutdown) {
            Socket socket = null;
            InputStream input = null;
            OutputStream output = null;
            try {
                //如果有客户端访问
                socket = serverSocket.accept();
                //获取输入流
                input = socket.getInputStream();
                //获取输出流
                output = socket.getOutputStream();
                //解析请求对象
                Request request = new Request(input);

//                //解析请求
                request.parse();
//
                //创建返回对象
                Response response = new Response(output);
                //设置请求参数
                response.setRequest(request);

                //  如果请求的是servlet
                if (request.getUri().startsWith("/servlet/")) {
                    ServletProcessor processor = new ServletProcessor();
                    processor.process(request, response);
                } else {
                    //请求的是静态资源
                    StaticResourceProcessor processor = new StaticResourceProcessor();
                    processor.process(request, response);
                }

                //关闭请求资源
                socket.close();
                //更改客户端状态
                shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
            } catch (Exception e) {
                e.printStackTrace();
                System.exit(1);
            }
        }
    }
}
